import {ActionCall} from "@/enums/message";
import emitter from "@/utils/emitter";

let ws = null;

class WebSocketClient {
    constructor(url) {
        this.url = url;
        this.websocket = null;
        this.heartbeatInterval = null;
        this.reconnectInterval = null;
        this.reconnectAttempts = 0;
        this.reconnectDelay = 10000; // 初始重连延迟时间（毫秒）10秒
        this.maxReconnectAttempts = 5;
    }

    start(id, token) {
        if ("WebSocket" in window) {
            console.log("当前浏览器支持 WebSocket");
            this.websocket = new WebSocket(this.url + `?token=${token}`);
        } else if ("MozWebSocket" in window) {
            console.log("当前浏览器支持 MozWebSocket");
            this.websocket = new MozWebSocket(this.url);
        } else {
            alert("当前浏览器不支持 WebSocket");
        }
        if (this.websocket) {
            // Websocket 连接成功回调方法
            this.websocket.onopen = (e) => {
                console.log("socket连接成功", e);
                clearInterval(this.reconnectInterval);
                this.reconnectInterval = null; // 确保定时器被完全清除
                this.startHeartbeat();
                this.reconnectAttempts = 0;
            };
            this.websocket.onmessage = (e) => {
                const data = JSON.parse(e.data);
                console.log("socket收到消息", data);
                if (data.action === ActionCall) {
                    emitter.emit("onCallMessage", data);
                } else {
                    emitter.emit("onMessage", data);
                }
            };

            this.websocket.onerror = (error) => {
                console.error('WebSocket连接error:', error);
                clearInterval(this.heartbeatInterval);
                this.heartbeatInterval = null;
                // this.reconnect(id, token); // 在这里直接调用reconnect方法
            };

            this.websocket.onclose = (e) => {
                console.error("socket连接close", e);
                console.log('定时器：', this.heartbeatInterval);
                clearInterval(this.heartbeatInterval);
                this.heartbeatInterval = null;

                clearInterval(this.reconnectInterval);
                this.reconnectInterval = null; // 确保定时器被完全清除
                this.reconnect(id, token); // 在这里直接调用reconnect方法
            };
        }

    }

    clearTimers() {
        clearInterval(this.heartbeatInterval);
        this.heartbeatInterval = null;
    }

    stop() {
        console.log('stop')
        if (this.websocket) {
            this.websocket.close();
        }
        clearInterval(this.heartbeatInterval);
        this.heartbeatInterval = null;

        clearInterval(this.reconnectInterval);
        this.reconnectInterval = null;

    }

    send(data) {
        if (this.websocket) {
            data = typeof data == "object" ? JSON.stringify(data) : data;
            console.log("发送消息", data);
            this.websocket.send(data);
        }
    }

    // 心跳检测
    startHeartbeat() {
        this.heartbeatInterval = setInterval(() => {
            const data = {
                who: "user",
                action: 'heartbeat',
                data: 'pong',
            };
            this.send(data);
            // 方法1：直接打印 Date 对象
            // console.log('当前时间:', new Date());
            // 方法2：使用 toLocaleString()
            console.log('当前时间:', new Date().toLocaleString());
        }, 10000); // 每30秒发送一次心跳
    }
    reconnect(id, token) {
        if (this.reconnectAttempts >= this.maxReconnectAttempts) {
            console.error(`最大重新连接尝试次数达到(${this.maxReconnectAttempts}) ,放弃重连。`);
            return;
        }
        this.reconnectAttempts++;
        console.log('定时器计数' + this.reconnectAttempts)
        // 递增重连延迟时间，使用指数退避算法递增重连延迟时间
        let currentDelay = Math.min(
            this.reconnectDelay * this.reconnectAttempts,
            60000); // 最大不超过60秒
        // 添加随机抖动（可选）
        const jitter = Math.random() * (currentDelay * 0.2); // 20% 的随机抖动
        currentDelay += jitter;
        console.log('重新连接延迟' + currentDelay)
        this.reconnectInterval = setTimeout(() => {
            console.error('reconnect socket 第' + this.reconnectAttempts + '次重连中。。。。[' + new Date().toLocaleString() + ']');
            this.start(id, token);
        }, currentDelay); // ？秒后重连
    }
}



if (ws == null){
    ws = new WebSocketClient(import.meta.env.VITE_APP_WEBSOCKET);
}


export default ws;



